import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.arnx.jsonic.JSON;
import net.arnx.jsonic.JSONException;

import org.sqlite.SQLiteDataSource;

public class JSONPServer extends Thread {
	public JSONPServer() {
		super();
		setDaemon(false);
	}
	
	public void run() {
		try {
			ServerSocket ss = new ServerSocket(80);
			System.out.println("webserver started.");

			while (true) {
				final Socket s = ss.accept();
				System.out.println("connected from " + s.getInetAddress());

				new Thread() {
					@Override
					public void run() {
						try {
							BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
							String req = r.readLine();

							if (req != null && (req.startsWith("GET") || req.startsWith("POST"))) {
								PrintWriter w = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), "utf-8"));
								w.println("HTTP/1.1 200 OK");
								w.println("Content-Type: text/javascript; charset=utf-8");
								w.println("Pragma: no-cache");
								w.println("Cache-Control: no-cache");
								w.println("Expires: Thu, 01 Dec 1994 16:00:00 GMT");
								w.println();

								String[] reqParams = req.split(" ");
								String url = reqParams[1];

								System.out.println(req);

								dispatch(url, r, w);

								w.flush();
							}

							s.close();
							System.out.println("disconnected from " + s.getInetAddress());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void dispatch(String url, BufferedReader r, PrintWriter w) throws Exception {
	}

	public Map<String, String> createParameterMap(String uri) {
		int qmark = uri.indexOf('?');
		Map<String, String> parameterMap = new HashMap<String, String>();

		if (qmark >= 0) {
			String[] queryStrings = uri.substring(qmark + 1).split("&");

			for (int i = 0; i < queryStrings.length; i++) {
				String[] kv = queryStrings[i].split("=");

				if (kv.length > 1) {
					parameterMap.put(URLDecoder.decode(kv[0]), URLDecoder.decode(kv[1]));
				}
			}
		}

		return parameterMap;
	}
}
